package com.macro.mall.es.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.common.dto.EsTableDto;
import com.macro.mall.common.dto.EsTableRes;
import com.macro.mall.es.service.EsTableService;
import com.macro.mall.model.PmsProutr;;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * es文档Service
 */
@Service
@Slf4j
public class EsTableServiceImpl implements EsTableService {
    @Resource
    private RestHighLevelClient restHighLevelClient;
    @Override
    public CommonResult doAddAll(List<PmsProutr> responseList) {
        BulkRequest bulkRequest = new BulkRequest();
        responseList.forEach(responseLists -> {
            bulkRequest.add(new IndexRequest("logs").id(responseLists.getId()+"").source(JSONObject.toJSONString(responseLists),XContentType.JSON));
        });
        try {
            restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("批量添加出现的异常：请求参数：{}，出现的异常：{}",JSONObject.toJSONString(responseList),e);
            throw new RuntimeException(e);
        }
        return CommonResult.success("添加成功");
    }

    @Override
    public void delAll(String indexName) {
        DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest(indexName);
        deleteByQueryRequest.setQuery(QueryBuilders.matchAllQuery());
        try {
            restHighLevelClient.deleteByQuery(deleteByQueryRequest,RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("删除全部出现的异常：请求参数：{}，出现的异常：{}",JSONObject.toJSONString(indexName),e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public void delEs(EsTableDto esTableDto) {
        DeleteRequest deleteRequest = new DeleteRequest(esTableDto.getIndexName(),esTableDto.getId());
        try {
            restHighLevelClient.delete(deleteRequest,RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("删除出现的异常：请求参数：{}，出现的异常：{}",JSONObject.toJSONString(esTableDto),e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public  Map<String,Object> search(EsTableRes esTableRes) {
        HashMap<String, Object> map = new HashMap<>();
        List<Object> objects = new ArrayList<>();
        try {
            SearchRequest searchRequest = new SearchRequest(esTableRes.getIndexName());
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            if (esTableRes.getKeyWord()!=null&&esTableRes.getSearchFields().getProductName()!=null){
                boolQueryBuilder.must(QueryBuilders.matchQuery(esTableRes.getSearchFields().getProductName(),esTableRes.getKeyWord()));
            }
            if (esTableRes.getKeyWord()!=null&&esTableRes.getSearchFields().getProductTitle()!=null){
                boolQueryBuilder.must(QueryBuilders.matchQuery(esTableRes.getSearchFields().getProductTitle(),esTableRes.getKeyWord()));
            }
            if (esTableRes.getKeyWord()!=null&&esTableRes.getSearchFields().getProductDesc()!=null){
                boolQueryBuilder.must(QueryBuilders.matchQuery(esTableRes.getSearchFields().getProductDesc(),esTableRes.getKeyWord()));
            }
            searchSourceBuilder.query(boolQueryBuilder);
            if (esTableRes.getPrice()!=null){
                if (esTableRes.getSort().equals("DESC")||esTableRes.getSort().equals("desc")){
                    searchSourceBuilder.sort(esTableRes.getPrice(), SortOrder.DESC);
                }else if (esTableRes.getSort().equals("ASC")||esTableRes.getSort().equals("asc")){
                    searchSourceBuilder.sort(esTableRes.getPrice(), SortOrder.ASC);
                }
            }
            if (esTableRes.getPageNum()!=null&&esTableRes.getPageSize()!=null){
                searchSourceBuilder.from((esTableRes.getPageNum()-1)*esTableRes.getPageSize());
                searchSourceBuilder.size(esTableRes.getPageSize());
            }
            searchRequest.source(searchSourceBuilder);
            SearchResponse search = restHighLevelClient.search(searchRequest,RequestOptions.DEFAULT);
            SearchHits hits = search.getHits();
            SearchHit[] hitsHits = hits.getHits();
            for (SearchHit hitsHit : hitsHits) {
                String sourceAsString = hitsHit.getSourceAsString();
                PmsProutr pmsProutr = JSONObject.parseObject(sourceAsString, PmsProutr.class);
                objects.add(pmsProutr);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        map.put(esTableRes.getIndexName(),objects);
        return map;
    }

}
